<template>
  <el-table
    v-if="reload"
    v-loading="loading"
    class="table-class"
    :data="tableData"
    border
    ref="table"
    row-key="id"
    lazy
    :load="load"
    :height="tableHeight"
    :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    :row-class-name="tableRowClassName"
    header-row-class-name="task-table-row-header"
    @selection-change="handleSelectionChange"
    @select="tableSelect"
    @select-all="tableSelectAll"
    @cell-mouse-enter="handleMouseEnter"
    @row-click="handleViewsTask1"
    style="width: 100%"
  >
    <!-- 选择框 -->
    <el-table-column
      type="selection"
      align="center"
      width="55"
    ></el-table-column>
    <!-- 任务名称 -->
    <el-table-column
      label="任务名称"
      width="400"
      class-name="title-row"
      sortable
      :sort-method="sortByTitle"
      show-overflow-tooltip
    >
      <template slot-scope="scope">
        <span class="task-badge" v-if="scope.row.canApprove"></span>
        <span style="vertical-align: text-top">{{ scope.row.title }}</span>
        <span v-if="scope.row.dbTypeName == '厂级督办' || scope.row.dbTypeName == '部门督办' && scope.row.duBan" :class="scope.row.dbTypeName == '厂级督办' ? 'redDuban' :'blueDuban'">督</span>
      </template>
    </el-table-column>
    <!-- 任务名称功能按钮··· -->
    <el-table-column
      align="center"
      label-class-name="setting-row"
      class-name="setting-row"
      width="35"
    >
      <template slot-scope="scope">
        <el-dropdown
          v-if="scope.row.canAddChild && !scope.row.folder"
          style="float: right"
          @command="handleMore($event, scope.row.taskId,scope.row)"
        >
          <el-button type="text" size="small" v-if="canEdit(scope.row.publishId)">
            <i class="el-icon-more el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <!-- <el-dropdown-item v-if="scope.row.taskLevel > 1" command="upgrade">升级</el-dropdown-item>-->
            <!-- <el-dropdown-item v-if="scope.row.taskLevel > 1" command="degrade">降级</el-dropdown-item>-->
            <el-dropdown-item
              command="createChild"  v-if="canEdit(scope.row.publishId)"
              >新建子任务</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown
          v-if="scope.row.publisher && scope.row.folder"
          v-show="showStopCycleTask"
          style="float: right"
          @command="handleMore($event, scope.row.taskId)"
        >
          <el-button type="text" size="small">
            <i class="el-icon-more el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown" v-if="showStopCycleTaskBtn">
            <el-dropdown-item command="startCycleTask"
              >启动周期任务</el-dropdown-item
            >
            <el-dropdown-item command="stopCycleTask"
              >停止周期任务</el-dropdown-item
            >
            <el-dropdown-item command="stopAndCloseCycleTask"
              >停止并删除周期任务</el-dropdown-item
            >
          </el-dropdown-menu>
          <el-dropdown-menu slot="dropdown" v-else>
            <el-dropdown-item command="restoreCycleTask"
              >恢复周期任务</el-dropdown-item
            >
            <el-dropdown-item command="restoreAndStartCycleTask"
              >恢复并启动周期任务</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
      </template>
    </el-table-column>
    <!-- 任务层级 -->
    <el-table-column
      label="任务层级"
      width="96"
      align="center"
      sortable
      :sort-method="sortByLevel"
    >
      <template slot-scope="scope">
        <span v-if="!!scope.row.taskLevel" class="task-level-span">{{
          scope.row.taskLevel
        }}</span>
      </template>
    </el-table-column>
    <!-- 负责部门 -->
    <el-table-column
      prop="managerDepartment"
      label="负责部门"
      width="150"
      sortable
      :sort-method="sortByManagerDepartment"
      show-overflow-tooltip
    ></el-table-column>
    <!-- 负责人 -->
    <el-table-column
      prop="manager"
      label="负责人"
      width="84"
      sortable
      :sort-method="sortByManager"
      show-overflow-tooltip
    ></el-table-column>
    <!-- 协办人 -->
    <el-table-column
      prop="joiners"
      label="协办人"
      width="84"
      sortable
      :sort-method="sortByPublisher"
      show-overflow-tooltip
    ></el-table-column>
    <!-- 督办人 -->
    <el-table-column
      prop="supervise"
      label="督办人"
      sortable
      :sort-method="sortByJoiners"
      show-overflow-tooltip
    ></el-table-column>
    
    <!-- 任务时间 -->
    <el-table-column
      label="任务时间"
      width="164"
      sortable
      :sort-method="sortTaskDate"
    >
      <template slot-scope="scope">
        <span v-if="!scope.row.folder"
          >{{ scope.row.startDate }} - {{ scope.row.endTime }}</span
        >
        <span v-else
          >{{ scope.row.cycleStart }} - {{ scope.row.cycleEnd }}</span
        >
      </template>
    </el-table-column>
    <!-- 任务进度 -->
    <el-table-column
      label="任务进度"
      width="140"
      sortable
      :sort-method="sortProcessRate"
    >
      <template slot-scope="scope">
        <el-progress
          v-if="!scope.row.folder"
          :text-inside="true"
          :stroke-width="20"
          :percentage="scope.row.processRate * 1"
          :color="customColorMethod(scope.row.state)"
        />
      </template>
    </el-table-column>
    <!-- 任务状态 -->
    <el-table-column
      label="任务状态"
      width="100"
      sortable
      :sort-method="sortState"
    >
      <template slot-scope="scope">
        <el-tag
          v-if="!!scope.row.state"
          effect="dark"
          style="border: none"
          :color="customColorMethod(scope.row.state)"
          size="mini"
          >{{ scope.row.state }}</el-tag
        >
      </template>
    </el-table-column>
    <!-- 审批状态 -->
    <el-table-column
      label="审批状态"
      width="100"
      sortable
      :sort-method="sortApproveState"
    >
      <template slot-scope="scope">
        <el-tag
          v-if="!!scope.row.approveState && !scope.row.folder"
          effect="dark"
          :type="appStateTypeMethod(scope.row.approveState)"
          size="mini"
          >{{ scope.row.approveState }}
        </el-tag>
      </template>
    </el-table-column>
    <!-- 紧急程度 -->
    <el-table-column
      label="紧急程度"
      width="100"
      sortable
      :sort-method="sortImportantLevel"
    >
      <template slot-scope="scope">
        <el-tag
          v-if="!!scope.row.importantLevel"
          effect="dark"
          :type="importLVTypeMethod(scope.row.importantLevel)"
          size="mini"
          >{{ scope.row.importantLevel }}
        </el-tag>
      </template>
    </el-table-column>
    <!--<el-table-column fixed="right" label="操作" width="64">
            <template slot-scope="scope">
                <el-button v-if="!scope.row.folder" @click="handleViewsTask(scope.row, false, $event)" type="text" size="small">查看</el-button>
                 <el-dropdown style="margin: 0 10px">
                    <el-button type="text" size="small">
                        更多
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="">执行</el-dropdown-item>
                        <el-dropdown-item command="">编辑任务</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
                </template>
            </el-table-column>-->
  </el-table>
</template>

<script>
import Sortable from 'sortablejs';
import Bus from './../bus';
import ApiTask from '../api';



export default {
    name: 'treeTable',
    props: [
        'defaultData',
        'tableHeight',
        'showStopCycleTask',
        'showStopCycleTaskBtn'
    ],
    data() {
        return {
            reload: true,
            tableData: JSON.parse(JSON.stringify(this.defaultData)) || [],
            selectionTaskId: '',
            startDrag: false,
            loading: false,
            rowList: [], //已加载的子节点
            checkIndeRow: [],
            currentUser: 0
        };
    },
    mounted() {
        this.getCurrentUser();
    // Bus.$off("checkAllTask").$on("checkAllTask", () => {
    //   this.checkAllTask();
    // });
    setTimeout(() => {
      console.log('this.tableData',this.tableData)
    }, 5000);
    },
    methods: {
        getCurrentUser() {
            ApiTask.getCurrentUser().then(res=>{
                const data = res.data;
                if (data.code === 0) {
                    this.currentUser = data.data;
                }
            });
        },
        sortByTitle(a, b) {
            return this.sortStrBy(a, b, 'title');
        },
        sortByLevel(a, b) {
            return this.sortBy(a, b, 'taskLevel');
        },
        sortByManager(a, b) {
            return this.sortStrBy(a, b, 'manager');
        },
        sortByPublisher(a, b) {
            return this.sortStrBy(a, b, 'publisher');
        },
        sortByJoiners(a, b) {
            return this.sortStrBy(a, b, 'joiners');
        },
        sortTaskDate(a, b) {
            return (
                new Date(a['startDate']).getTime() - new Date(b['startDate']).getTime()
            );
        },
        sortProcessRate(a, b) {
            return this.sortBy(a, b, 'processRate');
        },
        sortByManagerDepartment(a, b) {
            return this.sortStrBy(a, b, 'managerDepartment');
        },
        sortState(a, b) {
            return this.sortStrBy(a, b, 'state');
        },
        sortApproveState(a, b) {
            return this.sortStrBy(a, b, 'approveState');
        },
        sortImportantLevel(a, b) {
            return this.sortStrBy(a, b, 'importantLevel');
        },
        sortStrBy(a, b, prop) {
            return (a[prop] || '').localeCompare(b[prop] || '');
        },
        sortBy(a, b, prop) {
            return (a[prop] || 0) - (b[prop] || 0);
        },
        tableRowClassName({ row, rowIndex }) {
            if (!!row.folder) {
                return 'folder-row';
            }
            return '';
        },
        expandAll() {
            for (const row of this.rowList) {
                this.$refs.table.toggleRowExpansion(row, true);
            }
            // let els = document.getElementsByClassName('el-table__expand-icon')
            // if (this.tableData.length !== 0 && els.length !== 0) {
            //     for (let j = 0; j < els.length; j++) {
            //         els[j].classList.add('dafult')
            //     }
            //     if (this.$el.getElementsByClassName('el-table__expand-icon--expanded')) {
            //         const open = this.$el.getElementsByClassName('el-table__expand-icon--expanded')
            //         for (let j = 0; j < open.length; j++) {
            //             open[j].classList.remove('dafult')
            //         }
            //         const dafult = this.$el.getElementsByClassName('dafult')
            //         for (let a = 0; a < dafult.length; a++) {
            //             dafult[a].click()
            //         }
            //     }
            // }
        },
        collapseAll() {
            for (const row of this.rowList) {
                this.$refs.table.toggleRowExpansion(row, false);
            }
            // if (this.tableData.length !== 0) {
            //     const elsopen = this.$el.getElementsByClassName('el-table__expand-icon--expanded')
            //     if (this.$el.getElementsByClassName('el-table__expand-icon--expanded')) {
            //         for (let i = 0; i < elsopen.length; i++) {
            //             elsopen[i].click()
            //         }
            //     }
            // }
        },
        canEdit(actualPublishId) {
            return actualPublishId==this.currentUser;
        },
        handleMouseEnter(row) {
            if (this.startDrag) {
                //开始拖动后，选中该行
                this.$refs.table.clearSelection();
                this.$refs['table'].toggleRowSelection(row, true);
                this.selectionTaskId = row.taskId;
                //this.toggleRowExpansion(row, true);
            }
        },
        handleMore(command, taskId,taskData) {
            switch (command) {
                case 'copyCurrent':
                    Bus.$emit('copyCurrentTask', taskId);
                    break;
                case 'paste2Child':
                    Bus.$emit('paste2ChildTask', taskId);
                    break;
                case 'createChild':
                    Bus.$emit('addTableList', taskId,taskData);
                    console.log('新建子任务',taskData)
                    break;
                case 'upgrade':
                    Bus.$emit('changeUpGrade', taskId);
                    break;
                case 'degrade':
                    Bus.$emit('changeDeGrade', taskId);
                    break;
                case 'stopCycleTask':
                    Bus.$emit('stopCycleTask', taskId.split('.')[0]);
                    break;
                case 'startCycleTask':
                    Bus.$emit('startCycleTask', taskId.split('.')[0]);
                    break;
                case 'stopAndCloseCycleTask':
                    Bus.$emit('stopAndCloseCycleTask', taskId.split('.')[0]);
                    break;
                case 'restoreCycleTask':
                    Bus.$emit('restoreCycleTask', taskId.split('.')[0]);
                    break;
                case 'restoreAndStartCycleTask':
                    Bus.$emit('restoreAndStartCycleTask', taskId.split('.')[0]);
                    break;
                default:
                    break;
            }
        },
        //获取所有已展开的任务
        getAllUnfolded(rows) {
            const taskArr = [];
            if (rows) {
                rows.forEach(row => {
                    if (!row.folder) {
                        taskArr.push(row);
                    }
                    if (row.childrens) {
                        const children0 = this.getAllUnfolded(row.childrens);
                        children0.forEach(child => {
                            taskArr.push(child);
                        });
                    } else if (row.children) {
                        const children1 = this.getAllUnfolded(row.children);
                        children1.forEach(child => {
                            taskArr.push(child);
                        });
                    }
                });
            }
            return taskArr;
        },
        // checkAllTask() {
        //   let rows = this.tableData;
        //   console.log(rows);
        //   let res = this.getAllUnfolded(rows);
        //   if (res) {
        //     res.forEach(row => {
        //       this.$refs.table.toggleRowSelection(row);
        //     });
        //   } else {
        //     this.$refs.table.clearSelection();
        //   }
        // },
        tableSelectAll() {
            this.checkIndeRow = [];
            //获得子数据对象
            const children = this.$refs.table.store.states.lazyTreeNodeMap;
            //已选数组
            const select = this.$refs.table.store.states.selection;
            //全选状态
            const isAllSelect = this.$refs.table.store.states.isAllSelected;
            console.log(isAllSelect);
            if (isAllSelect) {
                for (const item in children) {
                    children[item].forEach((d, i) => {
                        if (select.indexOf(d) == -1 && !d.folder) {
                            select.push(d);
                        }
                    });
                }
            } else {
                this.$refs.table.store.states.selection = [];
            }
            this.handleSelectionChange(select);
        },
        tableSelect(selection, row) {
            const states = this.$refs.table.store.states;
            const children = states.lazyTreeNodeMap[row.id];
            const select = states.selection;
            // 如果半选数组中有被点击行，则半选状态肯定被取消
            const keyIndeRow = this.checkIndeRow.indexOf(row);
        },
        handleSelectionChange(val) {
            // 当前的点击实现勾选
            // this.$refs.table.clearSelection();
            // this.$refs.table.toggleRowSelection(row[row.length - 1], true);
            // this.selectionTaskId = row[row.length - 1].taskId;
            this.selectionTaskId = [];
            val.forEach(element => {
                if (!element.folder) {
                    this.selectionTaskId.push(element.taskId);
                }
            });
        },
        getSelectionTaskId(row) {
            return this.selectionTaskId;
        },
        clearSelection() {
            this.$refs.table.clearSelection();
            this.selectionTaskId = '';
        },
        setLoading(boo) {
            this.loading = boo;
        },
        //根据任务类型计算颜色
        customColorMethod(state) {
            let color = '#000';
            switch (state) {
                case '进行中':
                    color = '#409eff';
                    break;
                case '已完成':
                    color = '#004892';
                    break;
                case '已超期':
                    color = '#e60012';
                    break;
                case '已关闭':
                    color = '#909399';
                    break;
                case '未开始':
                    color = '#BEBEBE';
                    break;
                case '预警中':
                    color = '#EEAD0E';
                    break;
                case '已启用':
                    color = '#409eff';
                    break;
                case '已停止':
                    color = '#909399';
                    break;
                default:
                    color = '#000';
                    break;
            }
            return color;
        },
        importLVTypeMethod(importLV) {
            let type = '';
            switch (importLV) {
                case '一般':
                    type = 'info';
                    break;
                case '重要':
                    type = '';
                    break;
                case '紧急':
                    type = 'warning';
                    break;
                case '非常紧急':
                    type = 'danger';
                    break;
                default:
                    type = '';
                    break;
            }
            return type;
        },
        appStateTypeMethod(appState) {
            //正常、完成待审、正常完成、超期完成、被驳回、已关闭
            let type = 'success';
            switch (appState) {
                case '正常':
                case '正常完成':
                    type = 'success';
                    break;
                case '超期完成':
                    type = 'danger';
                    break;
                case '被驳回':
                case '完成待审':
                    type = 'warning';
                    break;
                case '已关闭':
                    type = 'info';
                    break;
                default:
                    type = '';
                    break;
            }
            return type;
        },
        rowDrop() {
            // 此时找到的元素是要拖拽元素的父容器
            const tbody = document.querySelector('.el-table__body-wrapper tbody');
            const _this = this;
            const data = [];
            Sortable.create(tbody, {
                draggable: '.el-table__row',
                delay: 80,
                fallbackTolerance: 5,
                sort: false,
                filter: '.folder-row',
                forceFallback: true,
                fallbackClass: 'sortable-fallback',
                onStart(obj) {
                    _this.startDrag = true;
                    _this.toggleRowExpansion(_this.tableData[obj.oldIndex], false);
                },
                onEnd(obj) {
                    //Bus.$emit('getTableList');
                    _this.startDrag = false;
                    Bus.$emit('tableDrag', obj);

                    //const targetRow = _this.tableData.splice(oldIndex, 1)[0];
                    //_this.tableData.splice(newIndex, 0, targetRow);
                    // 将 拖拽后的列表信息 存到 data变量中
                    //data = _this.tableData;
                    // 将 data变量中的 信息 赋值给 tableData 重新渲染列表数据
                    if (!!data.length) {
                        //Bus.$emit('setTableList', data);
                    }
                }
            });
        },
        toggleRowExpansion(row, open) {
            this.$refs['table'].toggleRowExpansion(row, open);
        },
        handleViewsTask(row, treeNode, e) {
            e && e.stopPropagation();
            Bus.$emit('viewTableList', { taskId: row.taskId, superId: row.superId });
        },
        handleViewsTask1(row, treeNode, e) {
            e && e.stopPropagation();
            if (row.folder) {
                return false;
            }
            Bus.$emit('viewTableList', { taskId: row.taskId, superId: row.superId });
        },
        load(tree, treeNode, resolve) {
            this.rowList.push(tree);
            Bus.$emit('getTableList', {
                resolve: resolve,
                isLoad: true,
                taskId: tree.taskId,
                folder: tree.folder,
                childrens: tree.childrens
            });
        }
    },
    watch: {
        defaultData: {
            handler: function (val) {
                this.reload = false;
                this.tableData = [];
                this.tableData.push(...val);
                this.$nextTick(() => {
                    this.reload = true;
                    this.loading = false;
                    this.$nextTick(() => {
                        this.rowDrop();
                    });
                });
            },
            deep: true
        }
    }
};
</script>
<style lang="scss" scoped>
.redDuban{
    display: inline-block;
    width: 16px;
    height: 16px;
    color: #e64219;
    border: 2px solid #e64219;
    // background-color: rgba(207, 105, 64, 0.5);
    border-radius: 50%;
    line-height: 16px;
    text-align: center;
    margin-left: 10px;
    vertical-align: text-top;
}
.blueDuban{
    display: inline-block;
    width: 16px;
    height: 16px;
    border: 2px solid #34a5d3;
    // background-color: rgba(135,206,235,0.5);
    border-radius: 50%;
    line-height: 16px;
    text-align: center;
    margin-left: 10px;
    vertical-align: text-top;
    color: #34a5d3;
}
.table-class /deep/ .title-row {
  border-right: none;
}
.table-class /deep/ .folder-row .title-row,
.table-class /deep/ .folder-row .setting-row {
  background-color: #eed596;
}
.table-class /deep/ .setting-row {
  border-left: none;
}
.table-class /deep/ .folder-row .el-checkbox {
  display: none;
}
.table-panel {
  padding: 10px;
  box-sizing: border-box;
}
.table-class /deep/ th,
.table-class /deep/ th {
  background: #fafafa;
}
.table-class /deep/ td,
.table-class /deep/ th {
  padding: 0px;
  height: 36px;
  font-size: 12px;
}
.table-class /deep/ .el-table__expand-icon {
  height: 32px;
  line-height: 32px;
}
.table-class /deep/ .el-table__expand-icon + span {
  vertical-align: middle !important;
}
.table-class /deep/ .el-tag--dark.el-tag--danger {
  background-color: #e60012;
}
// .table-class /deep/ .el-table__header-wrapper .el-table__header .el-checkbox {
//   display: none;
// }
.task-level-span {
  border: 2px solid #409eff;
  color: #409eff;
  font-size: 12px;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  text-align: center;
  line-height: 16px;
  display: inline-block;
}
.task-badge {
  position: absolute;
  top: 0;
  left: 0px;
  width: 0;
  height: 0;
  border-top: 16px solid #eead0e;
  border-right: 16px solid transparent;
}
</style>
